package online

import (
	"errors"
	"fmt"
	"server/im/entity"
	"sync"
)

var OnlineMap *HubOnline

func init() {
	OnlineMap = NewHubOnline()
}

func NewHubOnline() *HubOnline {
	return &HubOnline{
		onlineData: make(map[string]*HubOnlineItem),
		mu:         sync.Mutex{},
	}
}

type HubOnlineItem struct {
	User     entity.UserModel
	Gateways map[string]string
}

type HubOnline struct {
	onlineData map[string]*HubOnlineItem //map[uuid]user
	mu         sync.Mutex
}

func (o *HubOnline) GetOnline() map[string]*HubOnlineItem {
	return o.onlineData
}

func (o *HubOnline) Add(gatewayId string, user entity.UserModel) {
	o.mu.Lock()
	defer o.mu.Unlock()
	userUuid := user.Uuid
	onlineItem, ok := o.onlineData[userUuid]
	if ok {
		onlineItem.Gateways[gatewayId] = user.Ip
	} else {
		o.onlineData[userUuid] = &HubOnlineItem{
			User: user,
			Gateways: map[string]string{
				gatewayId: user.Ip,
			},
		}
	}

	fmt.Println(o.onlineData)

}

func (o *HubOnline) Remove(gatewayId string, user entity.UserModel) error {
	o.mu.Lock()
	defer o.mu.Unlock()
	userUuid := user.Uuid
	onlineItem, ok := o.onlineData[userUuid]
	if !ok {
		return errors.New("user not online")
	}
	delete(onlineItem.Gateways, gatewayId)
	if len(onlineItem.Gateways) == 0 {
		delete(o.onlineData, userUuid)
	}
	fmt.Println(o.onlineData)
	return nil
}

func (o *HubOnline) IsUserOnline(user entity.UserModel) bool {
	_, ok := o.onlineData[user.Uuid]
	return ok
}
